<template>
	<!-- 购物车页面 -->
	<div style="width: 100%;">
		<Header></Header>
		<div style="width:1200px;margin:auto;margin-top: 30px;">
			<el-table :data="goods" stripe style="width: 100%;text-align: center;">
				<el-table-column label="序号" width="100">
					<template #default="scope">
						{{scope.$index+1}}
					</template>
				</el-table-column>
				<el-table-column prop="imgs" label="图片" width="220">
					<template #default="scope">
						<img :src="'http://localhost:8080/' + scope.row.imgs" style="width: 80%;height: 100%;" />
					</template>
				</el-table-column>
				<el-table-column prop="goodsname" label="名称" width="150">
				</el-table-column>
				<el-table-column prop="price" label="单价" width="150">
				</el-table-column>
				<el-table-column prop="number" width="180" label="数量">
					<template #default="scope">
						<button @click="jian(scope.row)">-</button>
						{{scope.row.number}}
						<button @click="jia(scope.row)">+</button>
					</template>
				</el-table-column>
				<el-table-column label="总计" width="120">
					<template #default="scope">
						{{scope.row.price*scope.row.number}}
					</template>
				</el-table-column>
				<el-table-column label="操作">
					<template #default="scope">
						<el-button size="small" type='daner' @click="deleteCard(scope.row,scope.$index)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<div style="text-align: right;">
				<span style="font-size: 16px;color: red;padding:0px 30px">共计{{total}}元</span>
				<el-button type="primary" size='miduem' @click="showaddress" :disabled='goods.length==0'>结算</el-button>
			</div>
		</div>

		<!-- 选择收获地址对话框 -->
		<el-dialog v-model="show" title="收货地址" width="60%">
			<!-- 显示默认收货地址 -->
			<el-form :model="mrdz">
				<el-form-item label="" prop="youbian" label-width="600">
					<div style="font-size:16px;font-weight: 700;">收货人：{{mrdz.uname}} &nbsp;&nbsp; 电话：{{mrdz.utel}}
						&nbsp;&nbsp;
						地址：{{mrdz.sheng}} &nbsp;&nbsp;{{mrdz.city}} &nbsp;&nbsp;{{mrdz.qu}} &nbsp;&nbsp;{{mrdz.address}}
					</div>
				</el-form-item>
			</el-form>

			<!-- 显示用户所有收货地址 -->
			<el-table :data="dizhis" style="width: 100%">

				<el-table-column label="收货人" width="80">
					<template #default="scope">
						{{scope.row.uname}}
					</template>
				</el-table-column>
				<el-table-column label="电话" width="80">
					<template #default="scope">
						{{scope.row.utel}}
					</template>
				</el-table-column>
				<el-table-column label="详细地址" width="260">
					<template #default="scope">
						{{scope.row.sheng}}{{scope.row.shi}}{{scope.row.qu}}{{scope.row.address}}
					</template>
				</el-table-column>
				<el-table-column label="默认" width="70" prop='moren'>
					<template #default="scope">
						<div v-if="scope.row.moren==1">是</div>
						<div v-if="scope.row.moren==0">否</div>
					</template>
				</el-table-column>
				<el-table-column label="操作" width="80">
					<template #default="scope">
						<el-button size="small" type='daner' @click="xzdz(scope.row)">确认</el-button>
					</template>
				</el-table-column>
			</el-table>
			<br />
			<br />
			<el-button type="primary" @click="temp=1">添加地址</el-button>
			<br />
			<br />
			<!-- 添加收货地址 -->
			<el-form :model="shouhuo" v-if="temp==1" :rules="rules" ref="shouhuo">
				<el-form-item label="联系人" prop="uname" label-width="600">
					<el-input v-model="shouhuo.uname" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="联系电话" prop="utel" label-width="600">
					<el-input v-model="shouhuo.utel" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="省份" prop="sheng" label-width="600">
					<el-input v-model="shouhuo.sheng" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="城市" prop="city" label-width="600">
					<el-input v-model="shouhuo.city" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="区县" prop="qu" label-width="600">
					<el-input v-model="shouhuo.qu" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="详细地址" prop="address" label-width="600">
					<el-input v-model="shouhuo.address" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label-width="600">
					<el-button @click="temp = 0">取消</el-button>
					<el-button type="primary" @click="addDizhi('shouhuo')">添加</el-button>
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="show = false">取消</el-button>
					<el-button type="primary" @click="addOrders">下单</el-button>
				</span>
			</template>
		</el-dialog>

	</div>
</template>

<script>
	import Axios from 'axios'
	import {
		ElMessageBox,
		ElMessage
	} from 'element-plus'
	import router from "../route/index.js"
	import Header from './Header'
	export default {
		name: 'Cart',
		components: {
			Header
		},
		data() {
			return {
				goods: [], //购物车商品
				good: {},
				orders: {}, //订单
				users: {}, //用户
				order: {}, //订单对象
				num: 0, //总金额
				ordersdesc: [], //订单详情
				show: false, //对话框显示和隐藏
				shouhuo: {}, //添加的收货地址
				temp: 0, //控制添加表单显示和隐藏
				dizhis: [], //用户的所以收货地址
				mrdz: {}, //选中的收货地址
				rules: {
					uname: [{
						required: true,
						message: '请填写收货人',
						trigger: 'blur'
					}],
					sheng: [{
						required: true,
						message: '请填写省份',
						trigger: 'blur'
					}],
					city: [{
						required: true,
						message: '请填写城市',
						trigger: 'blur'
					}],
					qu: [{
						required: true,
						message: '请填写区县',
						trigger: 'blur'
					}],
					address: [{
						required: true,
						message: '请填写详细地址',
						trigger: 'blur'
					}],
					utel: [{
						required: true,
						message: '请填写联系电话',
						trigger: 'blur'
					}, {
						pattern: /^1([358][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$/,
						message: '请输入电话正确格式',
						trigger: 'blur'
					}]
				}
			}
		},
		computed: {
			total() { //计算总金额
				let sum = 0;
				for (let i = 0; i < this.goods.length; i++) {
					sum += this.goods[i].number * this.goods[i].price;
				}
				// this.num = sum;
				return sum;
			}
		},
		created() {
			this.getUsers();
			this.getAll();
		},
		methods: {
			xzdz(val) { //选择收货地址
				this.mrdz = val
			},
			addDizhi(shouhuo) { //添加收货地址
				this.$refs[shouhuo].validate(valid => {
					if (valid) {
						let dz = {
							uid: this.users.uid,
							uname: this.shouhuo.uname,
							utel: this.shouhuo.utel,
							sheng: this.shouhuo.sheng,
							city: this.shouhuo.city,
							qu: this.shouhuo.qu,
							address: this.shouhuo.address,
							moren: 0
						}
						Axios.post('/shopmng/api/dizhi/add', dz).then(res => {
							if (res.data.affectedRows == 1) {
								ElMessage({
									message: '添加成功',
									type: 'success',
								});
								this.temp = 0;
								this.dizhis.push(dz);
								this.shouhuo = {};
								this.showaddress()
							} else {
								ElMessage.error('添加失败')
							}
						});
					} else {
						return false
					}
				})
			},
			showaddress() { //查看用户的所有收货地址
				this.show = true;
				Axios.post('/shopmng/api/dizhi/selecUid', {
					'uid': this.users.uid
				}).then(res => {
					this.dizhis = res.data;
					for (let i = 0; i < this.dizhis.length; i++) {
						if (this.dizhis[i].moren == 1) {
							this.mrdz = this.dizhis[i];
							return;
						}
					}
				});
			},
			jia(row) {
				row.number += 1;
			},
			jian(row) {
				row.number -= 1;
			},
			getUsers() {
				// 获取sessionstorage中的用户信息
				let str = sessionStorage.getItem('users')
				if (str != null) {
					//把字符串转换成对象 --- sessionStorage存的必须时字符串，所以取出来的也是字符串
					this.users = JSON.parse(str);
				} else {
					ElMessage({
						message: '请先登录',
						type: 'info',
					});
					router.push('/Login')
				}
			},
			deleteCard(obj, index) { //删除商品
				ElMessageBox.confirm(
					'确认删除吗？', {
						confirmButtonText: '确认',
						cancelButtonText: '取消',
						type: 'warning',
					}
				).then(() => {
					Axios.post('/shopmng/api/card/deleteOne', {
						'cid': obj.cid
					}).then(res => {
						if (res.data.affectedRows == 1) {
							ElMessage({
								message: '删除成功',
								type: 'success',
							});
							this.getAll();
						} else {
							ElMessage({
								message: '删除失败',
							});
						}
					});

				})
			},
			getAll() { //获取用户的所有购物车商品
				Axios.post('/shopmng/api/card/selectAll', {
					'uid': this.users.uid
				}).then(res => {
					this.goods = res.data;
				});
			},
			addOrders() { //结算
				if (this.goods.length == 0) {
					ElMessage({
						type: 'info',
						message: '购物车没有商品，无法下单'
					})
					return;
				}
				if (this.mrdz.did == null) {
					ElMessage({
						type: 'info',
						message: '请先选择收货地址'
					})
					return;
				}
				let sum = 0;
				for (let i = 0; i < this.goods.length; i++) {
					sum += this.goods[i].number * this.goods[i].price;
				}
				this.num = sum;
				let date = new Date();
				let h = date.getHours();
				let m = date.getMinutes();
				let s = date.getSeconds();
				let y = date.getFullYear();
				let yue = date.getMonth();
				let ri = date.getDate();
				//定义唯一订单号
				let oid = this.users.uid + y + yue + ri + h + m + s + Math.ceil(Math.random() * 100);
				console.log(oid);
				// 定义订单信息
				this.order.oid = oid;
				this.order.uid = this.users.uid;
				this.order.num = this.num;
				this.order.dzid = this.mrdz.did;
				Axios.post('/shopmng/api/orders/insertOrders', this.order).then(res => {
					if (res.data.affectedRows > 0) {
						ElMessage({
							type: 'success',
							message: '订单已生成！',
						});
						this.show = false;
					} else {
						ElMessage({
							type: 'info',
							message: '订单已生成失败',
						})
					}
				});

				// 添加订单详情
				for (let i = 0; i < this.goods.length; i++) {
					this.ordersdesc[i] = {
						oid: oid,
						gid: this.goods[i].gid,
						number: this.goods[i].number,
						money: this.goods[i].price
					}
					Axios.post('/shopmng/api/ordersdesc/insertOrders', this.ordersdesc[i]).then(res => {});
				}

				// 更改库存，清空购物车
				for (let i = 0; i < this.goods.length; i++) {
					this.good[i] = {
						id: this.goods[i].gid,
						number: this.goods[i].number
					};
					// 更改库存
					Axios.post('shopmng/api/goods/updateNumber', this.good[i]).then(res => {
						if (res.data.affectedRows > 0) {
							console.info("库存减少")
						}
					})
					// 清空购物车
					Axios.post('/shopmng/api/card/deleteAll', {
						'uid': this.users.uid
					}).then(res => {
						this.getAll();
					});
				}


			}
		}
	}
</script>

<style>
</style>
